import React, {PureComponent} from "react";
import {Form, Icon, Input, InputNumber, notification, Popconfirm, Table, Tooltip} from "antd";
import {connect} from "react-redux";
import {paginationProps, tableProps} from "../../lib/ui";
import {
    del,
    getBaoGuanFeeByClientId,
    getBusinessCodeList,
    getClientList2,
    getCoach,
    getCurrencyList,
    getFeeList,
    getLines,
    getMyColumns,
    getTransportType,
    getVehicleFee,
    modifyPart,
    query,
    select,
    showEdit,
    updateBaoGuanFeeCount,
    updateDataSource,
    updateOrderFee,
    updateOrderOutFee
} from "./actions";
import {getColumnSet, getCurrentOrganization, getLastFilter, getPrincipal, saveColumnSet} from "../../lib/identity";
import {getLockStatus, getStatusText} from "../../lib/func";
import {getAllOrganization2} from "../organization/actions";
import NoInfo from "../../components/NoInfo";
import AddressInfo from "../../components/AddressInfo";
import {getCarrierList, getClientList, organizations} from "../home/actions";
import {query as vehicleQuery} from "../vehicle/actions";
import {query as lineQuery} from "../line/actions";
import {Resizable} from "react-resizable";

const LAST_FILTER = "ghOrder";

const EditableContext = React.createContext();

const EditableRow = ({form, index, ...props}) => (
    <EditableContext.Provider value={form}>
        <tr {...props} />
    </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
    state = {
        editing: false,
    };

    toggleEdit = () => {
        const editing = !this.state.editing;
        this.setState({editing}, () => {
            if (editing) {
                this.input.focus();
            }
        });
    };

    save = e => {
        const {record, handleSave} = this.props;
        this.form.validateFields((error, values) => {
            if (error && error[e.currentTarget.id]) {
                return;
            }
            this.toggleEdit();
            handleSave({...record, ...values});
        });
    };

    renderCell = form => {
        this.form = form;
        const {children, dataIndex, record, inputType} = this.props;
        const {editing} = this.state;
        return editing ? (
            <Form.Item style={{margin: 0}}>
                {form.getFieldDecorator(dataIndex, {
                    initialValue: record[dataIndex],
                })(inputType === "number" ?
                    <InputNumber ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save}/> :
                    <Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save}/>)}
            </Form.Item>
        ) : (
            <div
                className="editable-cell-value-wrap"
                style={{paddingRight: 24}}
                onClick={this.toggleEdit}
            >
                {children}
            </div>
        );
    };

    render() {
        const {
            editable,
            dataIndex,
            title,
            record,
            inputType,
            index,
            handleSave,
            children,
            valueField,
            labelField,
            ...restProps
        } = this.props;
        return (
            <td {...restProps}>
                {editable ? (
                    <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
                ) : (
                    children
                )}
            </td>
        );
    }
}

const ResizeableTitle = props => {
    const {onResize, width, ...restProps} = props;

    if (!width) {
        return <th {...restProps} />;
    }

    return (
        <Resizable
            width={width}
            height={0}
            onResize={onResize}
            draggableOpts={{enableUserSelectHack: false}}
        >
            <th {...restProps} />
        </Resizable>
    );
};

class List extends PureComponent {

    state = {rowId: "", columns: getColumnSet("ghOrder")};
    // 选中行
    onClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    rowId: record.id,
                });
            },
        };
    }
    setRowClassName = (record) => {
        if (record.status === "CONFIRMED" || record.settlement === "已结算" || record.outSettlement === "已结算") {
            return 'table-color-lock editable-row';
        }
        return record.id === this.state.rowId ? 'clickRowStyl editable-row' : 'editable-row';
    }

    onPageChange = (page, pageSize) => {
        const {dispatch, filter} = this.props;
        dispatch(query({
            "userId": getPrincipal().id,
            "organizationId": getCurrentOrganization(), ...filter,
            page,
            pageSize
        }));
    };

    handleShowEdit = row => {
        const {dispatch} = this.props;
        dispatch(getFeeList()).then(action => {
            if (action.error !== true) {
                dispatch(showEdit(row));
                dispatch(updateBaoGuanFeeCount(row));
                dispatch(updateOrderOutFee(row.outFeeList));
                dispatch(updateOrderFee(row.feeList));
                dispatch(getBusinessCodeList());
                dispatch(getCoach());
                dispatch(getLines({...row}));
                dispatch(getBaoGuanFeeByClientId(row.clientId));
                dispatch(getVehicleFee({"ownerId": row.clientId}));
                dispatch(getClientList2(getCurrentOrganization()));
            } else {
                notification.error({
                    message: '获取费用列表失败'
                });
            }
        });
    };

    handleDelete = id => {
        const {dispatch, page, pageSize, filter} = this.props;
        dispatch(del(id)).then(() => {
            dispatch(query({
                "userId": getPrincipal().id, ...filter,
                "organizationId": getCurrentOrganization(),
                page,
                pageSize
            }));
            notification.success({
                message: '删除成功'
            });
        });
    };

    handleSave = row => {
        if (row.status === "CONFIRMED") {
            notification.error({
                message: '已锁定,不能修改'
            });
            return;
        }
        const {dispatch, dataSource} = this.props;
        dispatch(modifyPart(row)).then(action => {
            if (action.error !== true) {
                let deleteIndex = dataSource.findIndex(item => item.id === row.id);
                dataSource.splice(deleteIndex, 1, row);
                dispatch(updateDataSource(dataSource));
            } else {
                notification.error({
                    message: '保存失败:' + action.message
                });
            }
        });
    };


    componentWillMount() {
        const {dispatch, page, pageSize} = this.props;
        dispatch(organizations(getPrincipal().id));
        dispatch(getMyColumns("ghOrder")).then(action => {
            if (action.error !== true) {
                let fields = getLastFilter(LAST_FILTER);
                if (fields === null || fields === undefined) {
                    fields = {};
                }
                dispatch(query({
                    "userId": getPrincipal().id,
                    "organizationId": getCurrentOrganization(),
                    ...fields,
                    page,
                    pageSize
                }));
                dispatch(getClientList(getCurrentOrganization()));
                dispatch(getClientList2(getCurrentOrganization()));
                dispatch(getAllOrganization2());
                dispatch(getCarrierList(getCurrentOrganization()));
                dispatch(getCurrencyList());
                dispatch(getTransportType());
                dispatch(vehicleQuery());
                dispatch(lineQuery({}));
            } else {
                notification.error({
                    message: '获取自定义列失败'
                });
            }
        });

    };

    handleSelectChange = (selectedRowKeys) => {
        const {dispatch} = this.props;
        dispatch(select(selectedRowKeys));
    };

    handleResize = index => (e, {size}) => {
        this.setState(({columns}) => {
            const nextColumns = [...columns];
            nextColumns[index] = {
                ...nextColumns[index],
                width: size.width,
            };
            return {columns: nextColumns};
        });
    };

    render() {
        const {
            page,
            pageSize,
            selectedRowKeys,
            totalElements,
            dataSource,
            loading,
            ghOrderColumns,
            columns,
        } = this.props;
        const rowSelection = {
            selectedRowKeys,
            columnWidth: '60px',
            onChange: this.handleSelectChange
        };
        const newColumns = [];
        const pageColumns = this.state.columns || getColumnSet("ghOrder");
        let isEmpty = false;
        if (columns.length === 0) {
            isEmpty = true;
        }
        ghOrderColumns.forEach(column => {
            // 从pageColumns中过滤出相同的列
            const foundColumn = pageColumns.find(item => item.value === column.value) || {};
            if (columns.indexOf(column.label) >= 0 || isEmpty) {
                if ("dateTime" === column.type) {
                    newColumns.push({
                        ...column,
                        ...foundColumn,
                        title: column.label,
                        dataIndex: column.value,
                        render: text => <span>{text && text.toString().substr(0, 10)}</span>
                    });
                } else if ("number" === column.type) {
                    newColumns.push({
                        ...column,
                        ...foundColumn,
                        title: column.label,
                        dataIndex: column.value,
                        render: text => <span>{text && Number(text).toFixed(3)}</span>
                    });
                } else if ("money" === column.type) {
                    newColumns.push({
                        ...column,
                        ...foundColumn,
                        title: column.label,
                        dataIndex: column.value,
                        render: text => <span>{text && Number(text).toFixed(2)}</span>
                    });
                } else if ("status" === column.type) {
                    newColumns.push({
                        ...column,
                        ...foundColumn,
                        title: '状态',
                        dataIndex: 'status',
                        width: column.width,
                        render: text => getLockStatus(text)
                    });
                } else if ("address" === column.type) {
                    newColumns.push({
                        ...column,
                        ...foundColumn,
                        title: column.label,
                        dataIndex: column.value,
                        render: (text) => <AddressInfo {...text}/>,
                        width: column.width
                    });
                } else if ('enum' === column.type) {
                    newColumns.push({
                        ...column,
                        ...foundColumn,
                        title: column.label,
                        dataIndex: column.value,
                        render: (text) => getStatusText(text, column.dataSource),
                        width: column.width
                    });
                } else if ('list' === column.type) {
                    newColumns.push({
                        ...column,
                        ...foundColumn,
                        title: column.label,
                        dataIndex: column.value,
                        render: (text, record) => <NoInfo item={record[column.dataKey]} valueLabel={column.itemKey}/>,
                        width: column.width
                    });
                } else {
                    if (column.clickable === true) {
                        newColumns.push({
                            ...column,
                            ...foundColumn,
                            title: column.label,
                            dataIndex: column.value,
                            render: (text, record) => (
                                <a
                                    onClick={() => {
                                        this.handleShowEdit(record);
                                    }}
                                >
                                    {text}
                                </a>
                            ),
                            width: column.width
                        });
                    } else {
                        if (column.render) {
                            newColumns.push({
                                ...column,
                                ...foundColumn,
                                title: column.label,
                                dataIndex: column.value,
                                render: column.render
                            });
                        } else {
                            newColumns.push({
                                ...column,
                                ...foundColumn,
                                title: column.label,
                                dataIndex: column.value,
                                ellipsis: true,
                                render: text => <Tooltip placement="top" title={text}>{text}</Tooltip>
                            });
                        }

                    }
                }
            }
        });
        if (getPrincipal().admin) {
            newColumns.push(
                {
                    title: '功能',
                    dataIndex: '',
                    key: 'x',
                    width: 50,
                    align: 'center',
                    fixed: 'right',
                    render: (text, record) => <span>
                    <Popconfirm title="确定删除此记录?" okText="是" cancelText="否"
                                onConfirm={() => this.handleDelete(record.id)}>
                        <Icon type="delete"/>
                    </Popconfirm>
                </span>,
                }
            );
        }
        const editColumns = newColumns.map((col, index) => {
            return {
                ...col,
                onCell: record => ({
                    record,
                    editable: col.editable,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    inputType: col.inputType,
                    handleSave: this.handleSave,
                }),
                onHeaderCell: column => ({
                    width: column.width,
                    onResize: this.handleResize(index),
                })
            };
        });

        saveColumnSet("ghOrder", newColumns);

        const resizeColumns = newColumns.map((col, index) => ({
            ...col,
            onHeaderCell: column => ({
                width: column.width,
                onResize: this.handleResize(index),
            }),
        }));

        const tablePagination = {
            ...paginationProps,
            total: totalElements,
            current: page,
            pageSize: pageSize,
            onShowSizeChange: (current, newSize) =>
                this.onPageChange && this.onPageChange(1, newSize),
            onChange: this.onPageChange
        };

        const components = {
            header: {
                cell: ResizeableTitle,
            },
        };

        return (
            <Table
                {...tableProps}
                columns={resizeColumns}
                components={components}
                scroll={{x: 1500, y: 'calc(100vh - 480px)'}}
                rowSelection={rowSelection}
                pagination={tablePagination}
                dataSource={dataSource}
                loading={loading}
                onRow={this.onClickRow}
                rowClassName={this.setRowClassName}
            />
        );
    }
}

const
    mapStateToProps = state => {
        return {
            ...state.ghOrder.list,
            calculateType: state.common.calculateType,
            ghOrderColumns: state.common.ghOrderColumns,
            columns: state.ghOrder.columns.columns
        };
    };

export default connect(mapStateToProps)(List);
